package ltd.newbee.mall.config.aop;

import lombok.extern.slf4j.Slf4j;
import ltd.newbee.mall.common.NewBeeMallException;
import ltd.newbee.mall.config.annotation.RequestRateLimiter;
import ltd.newbee.mall.util.IpUtils;
import ltd.newbee.mall.util.SpringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;

@Slf4j
@Component
@Aspect
@Order(999)
public class RateLimiterAspect {

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    @Resource
    private RedisScript<Long> limitScript;

    @Before(value = "@annotation(requestRateLimiter)")
    public void doBefore(JoinPoint point, RequestRateLimiter requestRateLimiter) throws Throwable {
        try {
            String key = requestRateLimiter.key();
            int time = requestRateLimiter.time();
            int count = requestRateLimiter.count();
            String combineKey = getCombineKey(requestRateLimiter, point);
            List<Object> keys = Collections.singletonList(combineKey);
            Long number = redisTemplate.execute(limitScript, keys, count, time);
            if (number == null || number.intValue() > count) {
                NewBeeMallException.fail("访问过于频繁，请稍候再试");
            }
            log.info("限制请求'{}',当前请求'{}',缓存key'{}'", count, number.intValue(), key);
        } catch (Exception e) {
            log.error("限流异常 limit = {}", e.getMessage());
            NewBeeMallException.fail("服务器限流异常，请稍候再试");
        }
    }

    public String getCombineKey(RequestRateLimiter rateLimiter, JoinPoint point) {
        StringBuilder stringBuffer = new StringBuilder(rateLimiter.key());
        if (rateLimiter.limitType() == RequestRateLimiter.LimitType.IP) {
            stringBuffer.append(IpUtils.getIpAddr(SpringUtils.currentRequest())).append("-");
        }
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Class<?> targetClass = method.getDeclaringClass();
        stringBuffer.append(targetClass.getName()).append("-").append(method.getName());
        return stringBuffer.toString();
    }
}
